import React, { Component } from 'react';
import {TransitionGroup, CSSTransition} from 'react-transition-group';
import Animate from 'react-smooth';
import {Motion, spring} from 'react-motion';

const styles = {
  width: 100,
  height: 100,
  background: 'orange',
  position: 'relative'
};

class Ani extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [
        {
          id: 1,
          text: 'aaa'
        },
        {
          id: 2,
          text: 'bbb'
        }
      ]
    }
  }
  // 添加列表
  addList = () => {
    this.setState({
      list: [
        ...this.state.list,
        {
          id: Math.round(Math.random() * 100000),
          text: this.refs.input.value
        }
      ],
      open: false
    });
    this.refs.input.value = '';
  }
  // 删除列表
  removeList = (id) => {
    this.setState({
      list: this.state.list.filter(item => item.id !== id)
    });
  }
  // 敲击回车
  handlePress = (e) => {
    if (e.charCode === 13) {
      this.addList();
      this.refs.input.blur();
    }
  }
  // switch
  handleSwitch = () => {
    this.setState({open: !this.state.open});
  }
  render() { 
    return (
      <div>
        <h2>动画合集</h2>
        <h3>TransitionGroup</h3>
        <input type="text" ref="input" onKeyPress={this.handlePress}/>
        <button onClick={this.addList}>添加</button>
        <ul>
          <TransitionGroup>
            {
              this.state.list.map(item => (
                <CSSTransition
                  key={item.id}
                  timeout={500}
                  classNames="fade"
                >
                  <li>
                    <button onClick={this.removeList.bind(this, item.id)}>&times;</button>
                    {item.text}
                  </li>
                </CSSTransition>
              ))
            }
          </TransitionGroup>
        </ul>

        <h3>弹簧动画</h3>
        <Animate from={{left: 0}} to={{left: 100}} easing="spring">
          <div style={styles}></div>
        </Animate>
        <h3>贝塞尔动画</h3>
        <Animate from={{left: 0}} to={{left: 200}} easing="ease">
            <div style={styles}></div>
        </Animate>
        <h3>开关</h3>
        <Motion style={{x: spring(this.state.open ? 50 : 0)}}>
          {
            ({x}) => (
              <div className="demo">
                <div className="demo-block" onClick={this.handleSwitch} style={{transform: `translateX(${x}px)`, background: this.state.open ? 'orange' : '#ccc'}}></div>
              </div>
            )
          }
        </Motion>
      </div>
    );
  }
}
 
export default Ani;